﻿using System;
using System.Data;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using EnumKeys;
using Webapp;
namespace xundh.API.House
{
    /// <summary>
    ///House_Rents 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.lansezhongjie.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]

    public class House_Rents : BaseService
    {
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys Add(int RentId, int Chu, int Wei, decimal HouseArea, int HouseFloor,
            int HouseTotalFloor, decimal TotalPrice, int Decoration, string CustomerName, string CustomerTel,
             string Mem, int RentRegionArea, bool HasKey,
            int RentFace, int RentBuildingId, string Dong, string Fang, decimal Shi, int Ting, int ViewLevel, string PayType
            )
        {
            ///Session
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.Model.RBAC_Users mUser = (xundh.Model.RBAC_Users)Session[EnumKeys.SessionKey.USER];
            ///变量
            DateTime now = DateTime.Now;
            string ip = HttpContext.Current.Request.UserHostAddress;
            ///参数处理
            CustomerName = StringUtil.CutBadSqlInfo(CustomerName.Trim());
            CustomerTel = StringUtil.CutBadSqlInfo(CustomerTel.Trim());
            Mem = StringUtil.CutBadSqlInfo(Mem);
            Dong = StringUtil.CutBadSqlInfo(Dong.Trim());
            Fang = StringUtil.CutBadSqlInfo(Fang.Trim());
            PayType = StringUtil.CutBadSqlInfo(PayType);

            xundh.BLL.House_Rents bll = new xundh.BLL.House_Rents();
            xundh.Model.House_Rents m;
            //用户权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();

            if (RentId > 0)
            {
                if (!serviceOperation.CheckResouceOperationLimit(mUser.UserId, "出租房源", "改")) return ServiceStateKeys.NoPermiss;
                m = bll.GetModel(RentId);
            }
            else
            {
                if (!serviceOperation.CheckResouceOperationLimit(mUser.UserId, "出租房源", "增")) return ServiceStateKeys.NoPermiss;
                m = new xundh.Model.House_Rents();

                m.AddUserId = mUser.UserId;
                m.AddUser = mUser.UserName;
                m.AddDepartId = mUser.DepartId;
                m.AddTime = now;
                m.AddIp = ip;
                m.FollowCount = 0;
                m.ViewCount = 0;
                m.State = (int)StateKeys.Normal;
            }
            m.Chu = Chu;
            m.Wei = Wei;
            m.HouseArea = HouseArea;
            m.HouseFloor = HouseFloor;
            m.HouseTotalFloor = HouseTotalFloor;
            m.TotalPrice = TotalPrice;
            m.Decoration = Decoration;
            m.CustomerName = CustomerName;
            m.CustomerTel = CustomerTel;
            m.ViewLevel = ViewLevel;
            m.LastUserId = mUser.UserId;
            m.LastUser = mUser.UserName;
            m.LastDepartId = mUser.DepartId;
            m.LastTime = now;
            m.LastIp = ip;
            m.Mem = Mem;
            m.RentRegionArea = RentRegionArea;
            m.HasKey = HasKey;
            m.PayType = PayType;
            if (HasKey)
                m.KeyDepartId = mUser.DepartId;
            m.RentFace = RentFace;
            m.RentBuildingId = RentBuildingId;
            m.Dong = Dong;
            m.Fang = Fang;
            m.Shi = Shi;
            m.Ting = Ting;
            if (RentId > 0)
                bll.Update(m);
            else
            {
                //不能重复登记
                string where = "RentBuildingId=" + RentBuildingId + " AND Dong='" + Dong + "' AND Fang='" + Fang + "' AND State=" + (int)StateKeys.Normal;
                int count = bll.GetRecordCount(where);
                if (count > 0)
                {
                    return ServiceStateKeys.Exists;
                }
                bll.Add(m);
            }
            ///更新房源数量
            Region.Region_Buildings serviceRegionBuilding = new Region.Region_Buildings();
            serviceRegionBuilding.Recalc("RentCount", RentBuildingId, GetCount(RentBuildingId));
            return ServiceStateKeys.Success;
        }
        /// <summary>
        /// 获取某小区的房源数量
        /// </summary>
        /// <param name="BuildingId"></param>
        /// <returns></returns>
        public int GetCount(int BuildingId)
        {
            xundh.BLL.House_Rents bll = new BLL.House_Rents();
            int count = bll.GetRecordCount("RentBuildingId=" + BuildingId);
            return count;
        }
        /// <summary>
        /// 获取某区域的房源数量
        /// </summary>
        /// <param name="BuildingId"></param>
        /// <returns></returns>
        public int GetRegionAreaCount(int RegionAreaId)
        {
            xundh.BLL.House_Rents bll = new BLL.House_Rents();
            int count = bll.GetRecordCount("RentRegionArea=" + RegionAreaId);
            return count;
        }
        /// <summary>
        /// 更新状态、单价、总价
        /// </summary>
        /// <param name="RentId"></param>
        /// <param name="UnitPrice"></param>
        /// <param name="TotalPrice"></param>
        /// <param name="State">-1代表不修改</param>
        /// <param name="ViewLevel">-1代表不修改</param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys UpdateState(int RentId, decimal TotalPrice, int State, int ViewLevel)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.Model.RBAC_Users mUser = (xundh.Model.RBAC_Users)HttpContext.Current.Session[EnumKeys.SessionKey.USER];
            ///参数处理
            if (RentId <= 0) return ServiceStateKeys.NotExists;


            xundh.BLL.House_Rents bll = new xundh.BLL.House_Rents();
            xundh.Model.House_Rents m;
            m = bll.GetModel(RentId);
            m.LastUserId = mUser.UserId;
            m.LastUser = mUser.UserName;
            m.LastTime = NOW;
            m.LastIp = IP;
            if (ViewLevel != -1) m.ViewLevel = ViewLevel;

            //用户权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(mUser.UserId, "出租房源", "改"))
            {
                ///没有房源修改权限的，如果自己房源，可以修改可见性
                if (U.UserId == m.AddUserId)
                {
                    bll.Update(m);
                    return ServiceStateKeys.Success;
                }
                return ServiceStateKeys.NoPermiss;
            }
            if (TotalPrice != 0) m.TotalPrice = TotalPrice;
            if (State != -1) m.State = State;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public JsonTable GetLists(int page, int rows)
        {
            if (U == null) return null;
            xundh.Model.RBAC_Users mUser = (xundh.Model.RBAC_Users)HttpContext.Current.Session[EnumKeys.SessionKey.USER];
            //角色权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(mUser.UserId, "出租房源", "查")) return null;

            xundh.BLL.BasePager bll = new BLL.BasePager();
            string RentRegionArea = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["RentRegionArea"]));
            int RentFace = StringUtil.Get_1Value(HttpContext.Current.Request["RentFace"]);
            int RentBuildingId = StringUtil.Get_1Value(HttpContext.Current.Request["RentBuildingId"]);
            string Address = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["Address"]));
            string Dong = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["Dong"]));
            string Fang = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["Fang"]));
            string CustomerTel = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["CustomerTel"]));
            int Shi = StringUtil.GetIntValue(HttpContext.Current.Request["Shi"]);
            int Ting = StringUtil.GetIntValue(HttpContext.Current.Request["Ting"]);
            decimal TotalPriceMin = StringUtil.GetDecimal(HttpContext.Current.Request["TotalPriceMin"]);
            decimal TotalPriceMax = StringUtil.GetDecimal(HttpContext.Current.Request["TotalPriceMax"]);
            decimal HouseAreaMin = StringUtil.GetDecimal(HttpContext.Current.Request["HouseAreaMin"]);
            decimal HouseAreaMax = StringUtil.GetDecimal(HttpContext.Current.Request["HouseAreaMax"]);
            int AddDepartId = StringUtil.Get_1Value(HttpContext.Current.Request["AddDepartId"]);
            int UserId = StringUtil.Get_1Value(HttpContext.Current.Request["UserId"]);
            int HouseFloorMin = StringUtil.GetIntValue(HttpContext.Current.Request["HouseFloorMin"]);
            int HouseFloorMax = StringUtil.GetIntValue(HttpContext.Current.Request["HouseFloorMax"]);
            int State = StringUtil.Get_1Value(HttpContext.Current.Request["State"]);
            int HasKey = StringUtil.Get_1Value(HttpContext.Current.Request["HasKey"]);
            string AddTimeMin = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["AddTimeMin"]));
            string AddTimeMax = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["AddTimeMax"]));
            int Decoration = StringUtil.Get_1Value(HttpContext.Current.Request["Decoration"]);
            int RentId = StringUtil.Get_1Value(HttpContext.Current.Request["RentId"]);

            string where = " 1=1 ";
            string table = "v_House_Rent_Buildings";
            if (RentRegionArea != "") where += " AND RentRegionArea in(" + RentRegionArea + ")";
            if (RentFace > -1) where += " AND RentFace=" + RentFace;
            if (RentBuildingId > -1) where += " AND BuildingId=" + RentBuildingId;
            if (Dong != "") where += " AND Dong='" + Dong + "'";
            if (Fang != "") where += " AND Fang='" + Fang + "'";
            if (CustomerTel != "") where += " AND CustomerTel LIKE '%" + CustomerTel + "%'";
            if (Shi > 0) where += " AND Shi=" + Shi;
            if (Ting > 0) where += " AND Ting=" + Ting;
            if (TotalPriceMin > 0) where += " AND TotalPrice>=" + TotalPriceMin;
            if (TotalPriceMax > 0) where += " AND TotalPrice<=" + TotalPriceMax;
            if (HouseAreaMin > 0) where += " AND HouseArea>=" + HouseAreaMin;
            if (HouseAreaMax > 0) where += " AND HouseArea<=" + HouseAreaMax;

            if (UserId > 0) { where += " AND AddUserId=" + UserId; }
            else
            {
                if (AddDepartId > 0)
                {
                    Org.Org_Departs serviceOrgDeparts = new Org.Org_Departs();
                    string departids = serviceOrgDeparts.GetStringsDepartsAndSons(AddDepartId);
                    departids = departids.ItemAdd(AddDepartId);
                    if (departids != "")
                        where += " AND AddDepartId in (" + departids + ")";
                }
            }
            if (HouseFloorMin > 0) where += " AND HouseFloor>=" + HouseFloorMin;
            if (HouseFloorMax > 0) where += " AND HouseFloor <=" + HouseFloorMax;
            if (State > -1) where += " AND State=" + State;
            else
                where += " AND State <>" + (int)HouseState.Delete;
            if (HasKey > -1) where += " AND HasKey=" + HasKey;
            if (StringUtil.isDate(AddTimeMin)) where += " AND AddTime>='" + AddTimeMin + "'";
            if (StringUtil.isDate(AddTimeMax)) where += " AND AddTime<='" + AddTimeMax + " 23:59:59'";
            if (Decoration > -1) where += " AND Decoration=" + Decoration;
            ///可见性权限，
            if (SystemGetBool("House", "IsAllowListPrivate"))
            {

            }
            else
            {
                //不允许列表查看私房
                where += " AND (";
                where += "    ( ViewLevel=" + (int)HouseViewLevel.Self + " AND AddUserId=" + mUser.UserId + ")";
                where += " OR ( ViewLevel=" + (int)HouseViewLevel.Depart + " AND AddDepartId=" + mUser.DepartId + ")";
                where += " OR ( ViewLevel=" + (int)HouseViewLevel.All + ")";
                where += " ) ";
            }
            if (RentId > 0) where += " AND RentId=" + RentId;
            JqGridHandler datagrid = new JqGridHandler(where);
            int recordcount = bll.GetAllCount(datagrid.StrWhere, table);
            string cols = "BuildingArea,BuildingAddr,BuildingAlice,BuildingName,BuildingLongitude,BuildingLatitude,BuildingNameEn,BuildingAliceEn,BuildingId,RentId,ViewLevel,RentRegionArea,RentFace,Dong,Fang,Shi,Ting,Chu,Wei,HouseArea,HouseFloor,HouseTotalFloor,TotalPrice,Decoration,CustomerName,AddUser,AddDepartId,AddTime,LastUserId,LastUser,LastDepartId,LastTime,Mem,HasKey,KeyDepartId,FollowCount,ViewCount,State";
            if (SystemGetBool("House", "IsUpdateHouseRentsList"))
                datagrid.init(datagrid.StrWhere, page, recordcount, rows, "LastTime", "Desc");
            else datagrid.init(datagrid.StrWhere, page, recordcount, rows, "RentId", "Desc");
            using (DataSet ds = bll.GetPager(datagrid.Pagesize, datagrid.P, datagrid.StrWhere, datagrid.Order, table, cols))
            {
                ///系统里列表是否显示楼栋号
                if (!SystemGetBool("House", "DongFangInList"))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        dr["Dong"] = "";
                        dr["Fang"] = "";
                    }
                }
                else
                {
                    //如果不许查看私房栋号
                    if (!SystemGetBool("House", "IsAllowViewPrivateDongFang"))
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            if (int.Parse(dr["ViewLevel"].ToString()) == (int)HouseViewLevel.Self)
                            {
                                dr["Dong"] = "";
                                dr["Fang"] = "";
                            }
                        }
                    }

                }
                JsonTable jt = new JsonTable(ds.Tables[0], recordcount, datagrid.P, datagrid.Recordcount);
                return jt;
            }
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public xundh.Model.House_Rents Query(int id)
        {
            if (U == null) return null;
            if (id <= 0) return null;

            xundh.Model.RBAC_Users mUser = (xundh.Model.RBAC_Users)HttpContext.Current.Session[EnumKeys.SessionKey.USER];
            //用户权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(mUser.UserId, "出租房源", "查")) return null;

            House_Rents_Views serviceView = new House_Rents_Views();
            //如果限制每天查询数量，就限制
            if (SystemGetBool("House", "IsViewCountLimit"))
            {
                int limitcount = SystemGetInt("House", "ViewCountLimit");
                int todayalready = serviceView.GetViewCount(mUser.UserId);
                if (todayalready >= limitcount) return null;
            }
            xundh.BLL.House_Rents bll = new xundh.BLL.House_Rents();
            xundh.Model.House_Rents m = bll.GetModel(id);
            bool hasLimit = true;
            if (mUser.UserAdmin)
            {
                //如果是管理员权限，则公，私盘号码都能看到
            }
            else
            {
                if (m.ViewLevel == (int)HouseViewLevel.All) { }
                else if (m.ViewLevel == (int)HouseViewLevel.Depart)
                {
                    if (m.AddDepartId != U.DepartId)
                    {
                        //没有权限
                        hasLimit = false;
                    }
                }
                else if (m.ViewLevel == (int)HouseViewLevel.Self)
                {
                    if (m.AddUserId != U.UserId) hasLimit = false;
                }
            }
            if (!hasLimit)
            {
                //私房限制，不允许查看私房栋号
                if (!SystemGetBool("House", "IsAllowViewPrivateDongFang"))
                {
                    m.Dong = ""; m.Fang = "";
                }
                m.CustomerTel = "";
            }
            ///生成一次查看记录
            serviceView.Add(id);
            return m;
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public ServiceStateKeys Delete(int id)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.Model.RBAC_Users mUser = (xundh.Model.RBAC_Users)HttpContext.Current.Session[EnumKeys.SessionKey.USER];
            xundh.BLL.House_Rents bll = new xundh.BLL.House_Rents();
            xundh.Model.House_Rents m = bll.GetModel(id);
            //角色权限
            bool hasLimit = false;
            ///如果允许删除自己的
            if (SystemGetBool("House", "IsAllowDeleteSelf"))
            {
                if (m.AddUserId == mUser.UserId) hasLimit = true;
            }
            if (!hasLimit)
            {
                RBAC.RBAC_Users serviceUsers = new RBAC.RBAC_Users();
                hasLimit = serviceUsers.CheckResouceOperationLimit(mUser.UserId, "出租房源", "删");
            }
            if (!hasLimit) return ServiceStateKeys.NoPermiss;

            ///删除
            m.State = (int)HouseState.Delete;
            m.LastTime = DateTime.Now;
            m.LastIp = HttpContext.Current.Request.UserHostAddress;
            m.LastUser = mUser.UserName;
            m.LastUserId = mUser.UserId;
            m.LastDepartId = mUser.DepartId;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }
        /// <summary>
        /// 更新楼盘id
        /// </summary>
        /// <param name="SellId"></param>
        /// <param name="UnitPrice"></param>
        /// <param name="TotalPrice"></param>
        /// <param name="State">-1代表不修改</param>
        /// <param name="ViewLevel">-1代表不修改</param>
        /// <returns></returns>
        //[WebMethod(EnableSession = true)]
        public ServiceStateKeys UpdateBuilding(int fromBuildingId, int toBuildingId)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            //用户权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "楼盘字典", "改"))
            {
                return ServiceStateKeys.NoPermiss;
            }
            Region.Region_Buildings serviceRegionBuildings = new Region.Region_Buildings();
            xundh.Model.Region_Buildings mBuild = serviceRegionBuildings.Query(toBuildingId);
            string sql = "UPDATE House_Rents SET RentBuildingId=" + toBuildingId + ",RentRegionArea=" + mBuild.BuildingArea + " WHERE RentBuildingId=" + fromBuildingId;
            xundh.BLL.BasePager bllP = new BLL.BasePager();
            bllP.GetGPager(sql);

            return ServiceStateKeys.Success;
        }
    }
}